<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统 - 通知管理</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="auth.js"></script>
    <script src="permission-control.js"></script>
</head>
<body>
    <!-- 主系统页面 -->
    <div id="mainPage" class="page active">
        <!-- 顶部导航栏 -->
        <header class="header">
            <div class="header-left">
                <button class="sidebar-toggle" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <h1 class="logo">
                    <i class="fas fa-book"></i>
                    图书馆管理系统
                </h1>
            </div>
            <div class="header-right">
                <div class="notification-icon" onclick="showNotifications()">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge" id="notificationBadge">0</span>
                </div>
                <div class="user-menu">
                    <span class="user-name" id="currentUserName">管理员</span>
                    <div class="user-dropdown">
                        <button class="dropdown-btn">
                            <i class="fas fa-user-circle"></i>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <div class="dropdown-content">
                            <a href="#" onclick="showProfile()">个人资料</a>
                            <a href="#" onclick="changePassword()">修改密码</a>
                            <a href="#" onclick="logout()">退出登录</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- 侧边栏 -->
        <aside class="sidebar" id="sidebar">
            <nav class="sidebar-nav">
                <ul id="sidebarMenu">
                    <!-- 菜单将通过JavaScript动态生成 -->
                </ul>
            </nav>
        </aside>

        <!-- 主内容区域 -->
        <main class="main-content">
            <!-- 通知管理页面 -->
            <div id="notifications" class="content-page active">
                <div class="page-header">
                    <h2>通知管理</h2>
                    <div class="header-actions">
                        <button class="btn btn-success" onclick="markAllAsRead()">
                            <i class="fas fa-check-double"></i>
                            全部标记为已读
                        </button>
                        <button class="btn btn-primary" onclick="showAddNotificationModal()">
                            <i class="fas fa-plus"></i>
                            发送通知
                        </button>
                    </div>
                </div>
                <div class="page-filters">
                    <div class="filter-group">
                        <select id="notificationTypeFilter" class="form-control">
                            <option value="">所有类型</option>
                            <option value="1">系统通知</option>
                            <option value="2">借阅提醒</option>
                            <option value="3">还书提醒</option>
                            <option value="4">逾期提醒</option>
                            <option value="5">罚款通知</option>
                        </select>
                        <select id="notificationReadFilter" class="form-control">
                            <option value="">所有状态</option>
                            <option value="false">未读</option>
                            <option value="true">已读</option>
                        </select>
                        <button class="btn btn-secondary" onclick="searchNotifications()">
                            <i class="fas fa-search"></i>
                            搜索
                        </button>
                    </div>
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="selectAllCheckbox" onclick="toggleSelectAll()"></th>
                                <th>ID</th>
                                <th>接收用户</th>
                                <th>通知类型</th>
                                <th>标题</th>
                                <th>内容</th>
                                <th>通知方式</th>
                                <th>发送时间</th>
                                <th>阅读状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="notificationTableBody">
                        </tbody>
                    </table>
                </div>
                <div class="batch-actions">
                    <button class="btn btn-success" onclick="batchMarkAsRead()">
                        <i class="fas fa-check"></i>
                        批量标记为已读
                    </button>
                </div>
                <div class="pagination" id="notificationPagination">
                </div>
            </div>
        </main>
    </div>

    <!-- 模态框 -->
    <div id="modalOverlay" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h3 id="modalTitle">标题</h3>
                <button class="modal-close" onclick="closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body" id="modalBody">
            </div>
            <div class="modal-footer" id="modalFooter">
            </div>
        </div>
    </div>

    <!-- 加载提示 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner">
            <i class="fas fa-spinner fa-spin"></i>
            <p>加载中...</p>
        </div>
    </div>

    <!-- 消息提示 -->
    <div id="messageContainer" class="message-container">
    </div>

    <script src="api.js"></script>
    <script>
        // 全局变量
        let currentUser = null;
        let currentPageNum = 1;
        let currentPageSize = 10;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeApp();
        });

        // 初始化应用
        function initializeApp() {
            // 检查页面访问权限
            if (!PermissionControl.checkPageAccess()) {
                return;
            }
            
            // 获取当前用户信息
            currentUser = authManager.getCurrentUser();
            if (!currentUser) {
                Utils.showMessage('用户信息获取失败，请重新登录', 'error');
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 2000);
                return;
            }
            
            // 生成侧边栏菜单
            generateSidebarMenu();

            // 更新用户信息
            document.getElementById('currentUserName').textContent = currentUser.realName || currentUser.username;

            // 加载未读通知数量
            loadUnreadNotificationCount();
            
            // 加载通知数据
            loadNotifications();
        }

        // 加载未读通知数量
        async function loadUnreadNotificationCount() {
            try {
                const response = await NotificationAPI.countUnreadNotifications(currentUser.userId);
                if (response.result === 'SUCCESS') {
                    const count = response.data || 0;
                    const badge = document.getElementById('notificationBadge');
                    if (badge) {
                        badge.textContent = count;
                        badge.style.display = count > 0 ? 'block' : 'none';
                    }
                } else {
                    Utils.showMessage(response.message || '加载通知数量失败', 'error');
                    console.error('加载通知数量失败:', response.message);
                }
            } catch (error) {
                Utils.showMessage('加载通知数量失败: ' + error.message, 'error');
                console.error('Load unread notification count error:', error);
            }
        }

        // 生成侧边栏菜单
        function generateSidebarMenu() {
            const sidebarMenu = document.getElementById('sidebarMenu');
            if (sidebarMenu && authManager) {
                sidebarMenu.innerHTML = authManager.generateSidebarMenu();
            }
        }

        // 检查登录状态
        function checkLoginStatus() {
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                currentUser = JSON.parse(savedUser);
            }
        }

        // 切换侧边栏
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('active');
        }

        // 退出登录
        function logout() {
            currentUser = null;
            localStorage.removeItem('currentUser');
            window.location.href = 'login.html';
            Utils.showMessage('已退出登录', 'info');
        }

        // 显示通知
        function showNotifications() {
            window.location.href = 'notifications.html';
        }

        // 显示个人资料
        function showProfile() {
            Utils.showMessage('个人资料功能开发中', 'info');
        }

        // 修改密码
        function changePassword() {
            Utils.showMessage('修改密码功能开发中', 'info');
        }

        // 加载通知数据
        async function loadNotifications(page = 1) {
            try {
                Utils.showLoading();

                const type = document.getElementById('notificationTypeFilter')?.value || '';
                const isRead = document.getElementById('notificationReadFilter')?.value || '';

                const response = await NotificationAPI.pageUserNotifications(page, currentPageSize, '', type, isRead);

                if (response.result === 'SUCCESS') {
                    renderNotificationTable(response.data.records);
                    renderPagination('notificationPagination', page, response.data.pages, loadNotifications);
                } else {
                    Utils.showMessage(response.message || '加载通知数据失败', 'error');
                    console.error('加载通知数据失败:', response.message);
                }
            } catch (error) {
                Utils.showMessage('加载通知数据失败: ' + error.message, 'error');
                console.error('Notifications load error:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 渲染通知表格
        function renderNotificationTable(notifications) {
            const tbody = document.getElementById('notificationTableBody');
            if (!tbody) return;

            tbody.innerHTML = notifications.map(notification => `
                <tr>
                    <td><input type="checkbox" class="notification-checkbox" value="${notification.notificationId}" ${notification.readStatus === 'read' ? 'disabled' : ''}></td>
                    <td>${notification.notificationId || '未知'}</td>
                    <td>${notification.realName || notification.username || '系统通知'}</td>
                    <td>${getNotificationTypeText(notification.type)}</td>
                    <td>${notification.title}</td>
                    <td>${notification.content.length > 50 ? notification.content.substring(0, 50) + '...' : notification.content}</td>
                    <td>${getNotificationWayText(notification.notifyWay)}</td>
                    <td>${Utils.formatDate(notification.sendTime)}</td>
                    <td><span class="status-badge status-${notification.readStatus === 'read' ? 'read' : 'unread'}">${notification.readStatus === 'read' ? '已读' : '未读'}</span></td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="viewNotificationDetail(${notification.notificationId || 0})">详情</button>
                        ${notification.readStatus !== 'read' ? `
                            <button class="btn btn-sm btn-success" onclick="markAsRead(${notification.notificationId || 0})">标记已读</button>
                        ` : ''}
                        <button class="btn btn-sm btn-danger" onclick="deleteNotification(${notification.notificationId || 0})">删除</button>
                    </td>
                </tr>
            `).join('');
        }

        // 获取通知类型文本
        function getNotificationTypeText(type) {
            const typeMap = {
                1: '系统通知',
                2: '借阅提醒',
                3: '还书提醒',
                4: '逾期提醒',
                5: '罚款通知'
            };
            // 如果type是字符串（数据库中的枚举值），则进行映射
            if (typeof type === 'string') {
                const stringTypeMap = {
                    'announcement': '系统通知',
                    'borrow_notify': '借阅提醒',
                    'return_notify': '还书提醒',
                    'overdue_notify': '逾期提醒',
                    'fine_notify': '罚款通知',
                    'due_reminder': '逾期提醒',
                    'reservation_notify': '借阅提醒',
                    'borrow_reminder': '借阅提醒',
                    'return_reminder': '还书提醒'
                };
                return stringTypeMap[type] || '未知类型';
            }
            // 如果type是数字（前端代码中的类型代码），则使用原来的映射
            return typeMap[type] || '未知类型';
        }

        // 获取通知方式文本
        function getNotificationWayText(way) {
            const wayMap = {
                'email': '邮件',
                'system': '系统'
            };
            return wayMap[way] || way;
        }

        // 搜索通知
        function searchNotifications() {
            currentPageNum = 1;
            loadNotifications(1);
        }

        // 显示添加通知模态框
        function showAddNotificationModal() {
            showModal('发送通知', `
                <form id="addNotificationForm">
                    <div class="form-group">
                        <label for="addNotificationType">通知类型</label>
                        <select id="addNotificationType" name="type" required>
                            <option value="">请选择类型</option>
                            <option value="1">系统通知</option>
                            <option value="2">借阅提醒</option>
                            <option value="3">还书提醒</option>
                            <option value="4">逾期提醒</option>
                            <option value="5">罚款通知</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="addNotificationTitle">标题</label>
                        <input type="text" id="addNotificationTitle" name="title" required>
                    </div>
                    <div class="form-group">
                        <label for="addNotificationContent">内容</label>
                        <textarea id="addNotificationContent" name="content" rows="4" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="addNotificationWay">通知方式</label>
                        <select id="addNotificationWay" name="notifyWay" required>
                            <option value="system">系统通知</option>
                            <option value="email">邮件通知</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="addNotificationUserId">接收用户 (留空表示系统公告)</label>
                        <select id="addNotificationUserId" name="userId">
                            <option value="">系统公告</option>
                        </select>
                    </div>
                </form>
            `, `
                <button class="btn btn-primary" onclick="submitAddNotification()">发送</button>
                <button class="btn btn-secondary" onclick="closeModal()">取消</button>
            `);

            // 加载用户数据
            loadUsersForNotification();
        }

        // 加载用户数据到通知选择框
        async function loadUsersForNotification() {
            try {
                const response = await UserAPI.pageUsers(1, 100);
                if (response.result === 'SUCCESS') {
                    const users = response.data.records;
                    const select = document.getElementById('addNotificationUserId');
                    if (select) {
                        select.innerHTML = '<option value="">系统公告</option>' +
                            users.map(user => `<option value="${user.userId}">${user.realName} (${user.username})</option>`).join('');
                    }
                } else {
                    Utils.showMessage(response.message || '加载用户数据失败', 'error');
                    console.error('加载用户数据失败:', response.message);
                }
            } catch (error) {
                Utils.showMessage('加载用户数据失败: ' + error.message, 'error');
                console.error('Load users for notification error:', error);
            }
        }

        // 提交添加通知
        async function submitAddNotification() {
            const form = document.getElementById('addNotificationForm');
            const formData = new FormData(form);

            const notificationData = {
                type: parseInt(formData.get('type')),
                title: formData.get('title'),
                content: formData.get('content'),
                notifyWay: formData.get('notifyWay'),
                userId: formData.get('userId') ? parseInt(formData.get('userId')) : null
            };

            try {
                Utils.showLoading();
                const response = await NotificationAPI.createNotification(notificationData);

                if (response.result === 'SUCCESS') {
                    Utils.showMessage('通知发送成功', 'success');
                    closeModal();
                    loadNotifications();
                    // 重新加载通知数量
                    await loadUnreadNotificationCount();
                } else {
                    Utils.showMessage(response.message || '发送通知失败', 'error');
                    console.error('发送通知失败:', response.message);
                }
            } catch (error) {
                Utils.showMessage('发送通知失败: ' + error.message, 'error');
                console.error('发送通知异常:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 查看通知详情
        async function viewNotificationDetail(notificationId) {
            // 检查notificationId有效性
            if (!notificationId || isNaN(notificationId) || notificationId <= 0) {
                Utils.showMessage('无效的通知ID', 'error');
                return;
            }

            try {
                Utils.showLoading();
                const response = await NotificationAPI.getNotificationById(notificationId);

                if (response.result === 'SUCCESS') {
                    const notification = response.data;
                    showModal('通知详情', `
                        <div class="notification-detail">
                            <div class="detail-row">
                                <label>通知ID:</label>
                                <span>${notification.notificationId || '未知'}</span>
                            </div>
                            <div class="detail-row">
                                <label>接收用户:</label>
                                <span>${notification.realName || notification.username || '系统公告'}</span>
                            </div>
                            <div class="detail-row">
                                <label>通知类型:</label>
                                <span>${getNotificationTypeText(notification.type)}</span>
                            </div>
                            <div class="detail-row">
                                <label>标题:</label>
                                <span>${notification.title}</span>
                            </div>
                            <div class="detail-row">
                                <label>内容:</label>
                                <div class="notification-content">${notification.content}</div>
                            </div>
                            <div class="detail-row">
                                <label>通知方式:</label>
                                <span>${getNotificationWayText(notification.notifyWay)}</span>
                            </div>
                            <div class="detail-row">
                                <label>发送时间:</label>
                                <span>${Utils.formatDate(notification.sendTime)}</span>
                            </div>
                            <div class="detail-row">
                                <label>阅读状态:</label>
                                <span class="status-badge status-${notification.readStatus === 'read' ? 'read' : 'unread'}">${notification.readStatus === 'read' ? '已读' : '未读'}</span>
                            </div>
                        </div>
                    `, `
                        ${notification.readStatus !== 'read' ? `
                            <button class="btn btn-success" onclick="markAsRead(${notification.notificationId || 0}); closeModal();">标记已读</button>
                        ` : ''}
                        <button class="btn btn-secondary" onclick="closeModal()">关闭</button>
                    `);
                } else {
                    Utils.showMessage(response.message || '获取通知详情失败', 'error');
                    console.error('获取通知详情失败:', response.message);
                }
            } catch (error) {
                Utils.showMessage('获取通知详情失败: ' + error.message, 'error');
                console.error('获取通知详情异常:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 标记为已读
        async function markAsRead(notificationId) {
            // 检查notificationId有效性
            if (!notificationId || isNaN(notificationId) || notificationId <= 0) {
                Utils.showMessage('无效的通知ID', 'error');
                return;
            }

            try {
                Utils.showLoading();
                const response = await NotificationAPI.markAsRead(notificationId);

                if (response.result === 'SUCCESS') {
                    Utils.showMessage('已标记为已读', 'success');
                    loadNotifications();
                    // 重新加载通知数量
                    await loadUnreadNotificationCount();
                } else {
                    Utils.showMessage(response.message || '标记失败', 'error');
                    console.error('标记已读失败:', response.message);
                }
            } catch (error) {
                Utils.showMessage('标记失败: ' + error.message, 'error');
                console.error('标记已读异常:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 批量标记为已读
        async function markAllAsRead() {
            if (!confirm('确定要将所有通知标记为已读吗？')) return;

            try {
                Utils.showLoading();
                const response = await NotificationAPI.markAllAsRead(currentUser.userId);

                if (response.result === 'SUCCESS') {
                    Utils.showMessage('所有通知已标记为已读', 'success');
                    loadNotifications();
                    // 重新加载通知数量
                    await loadUnreadNotificationCount();
                } else {
                    Utils.showMessage(response.message || '标记失败', 'error');
                    console.error('批量标记已读失败:', response.message);
                }
            } catch (error) {
                Utils.showMessage('标记失败: ' + error.message, 'error');
                console.error('批量标记已读异常:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 批量标记选中为已读
        async function batchMarkAsRead() {
            // 获取所有选中的通知ID
            const checkboxes = document.querySelectorAll('.notification-checkbox:checked');
            const notificationIds = Array.from(checkboxes).map(cb => parseInt(cb.value));

            if (notificationIds.length === 0) {
                Utils.showMessage('请至少选择一个通知', 'warning');
                return;
            }

            if (!confirm(`确定要将选中的 ${notificationIds.length} 个通知标记为已读吗？`)) return;

            try {
                Utils.showLoading();
                const response = await NotificationAPI.batchMarkAsRead(notificationIds);

                if (response.result === 'SUCCESS') {
                    Utils.showMessage(`成功标记 ${notificationIds.length} 个通知为已读`, 'success');
                    loadNotifications();
                    // 重新加载通知数量
                    await loadUnreadNotificationCount();
                } else {
                    Utils.showMessage(response.message || '标记失败', 'error');
                    console.error('批量标记已读失败:', response.message);
                }
            } catch (error) {
                Utils.showMessage('标记失败: ' + error.message, 'error');
                console.error('批量标记已读异常:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 删除通知
        async function deleteNotification(notificationId) {
            // 检查notificationId有效性
            if (!notificationId || isNaN(notificationId) || notificationId <= 0) {
                Utils.showMessage('无效的通知ID', 'error');
                return;
            }

            if (!confirm('确定要删除该通知吗？')) return;

            try {
                Utils.showLoading();
                const response = await NotificationAPI.deleteNotification(notificationId);

                if (response.result === 'SUCCESS') {
                    Utils.showMessage('通知删除成功', 'success');
                    loadNotifications();
                    // 重新加载通知数量
                    await loadUnreadNotificationCount();
                } else {
                    Utils.showMessage(response.message || '删除通知失败', 'error');
                    console.error('删除通知失败:', response.message);
                }
            } catch (error) {
                Utils.showMessage('删除通知失败: ' + error.message, 'error');
                console.error('删除通知异常:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 显示模态框
        function showModal(title, body, footer) {
            document.getElementById('modalTitle').textContent = title;
            document.getElementById('modalBody').innerHTML = body;
            document.getElementById('modalFooter').innerHTML = footer;
            document.getElementById('modalOverlay').classList.add('active');
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('modalOverlay').classList.remove('active');
        }

        // 全选/取消全选
        function toggleSelectAll() {
            const selectAllCheckbox = document.getElementById('selectAllCheckbox');
            const checkboxes = document.querySelectorAll('.notification-checkbox');
            checkboxes.forEach(checkbox => {
                if (!checkbox.disabled) {
                    checkbox.checked = selectAllCheckbox.checked;
                }
            });
        }

        // 渲染分页组件
        function renderPagination(containerId, currentPage, totalPages, onPageChange) {
            const container = document.getElementById(containerId);
            if (!container) return;

            if (totalPages <= 1) {
                container.innerHTML = '';
                return;
            }

            container.innerHTML = '';
            container.appendChild(Utils.createPagination(currentPage, totalPages, onPageChange));
        }
    </script>
</body>
</html>
